var method;
var link;
var data = new FormData();
var payload = {};

window.onload = init;


async function init () {
    method = document.getElementById("method").innerHTML;
    link = document.getElementById("link").innerHTML;
};

async function make_request(){
    await init();
    if (method == "GET"){
        await get_path_parametrs();
        await get_query_parametrs();
    }
    if (method == "POST"){
        await get_path_parametrs();
        await get_post_parametrs();
    }
    if (method == "PUT"){
        await get_path_parametrs();
        await get_post_parametrs();
    }

    if (method == "DELETE"){
        await get_path_parametrs();
    }

    request();
}

async function get_path_parametrs(){
    let path_params = document.getElementById("path");
    const collection = path_params.children;
    for (let i = 0; i < collection.length; i++) {
        key = collection[i].name;
        value = collection[i].value;
        from_str = "{".concat(key).concat("}");
        link = link.replace(from_str, value);
    }
}

async function get_query_parametrs(){
    link = link.replace("?", "");
    link = link.concat("?");
    let c = 0;
    let adding;
    let query_params = document.getElementById("query");
    const collection = query_params.children;
    for (let i = 0; i < collection.length; i++) {
        if (collection[i].value !== undefined && collection[i].value != ""){
            adding = `${collection[i].name}=${collection[i].value}&`;
            link = link.concat(adding);
            c += 1;
        }
    }
    if (c == 0){
        link = link.replace("?", "");
    }
}

async function get_post_parametrs(){
    let post_params = document.getElementById("post");
    const collection = post_params.children;
    for (let i = 0; i < collection.length; i++) {
        key = collection[i].name;
        value = collection[i].value;
        payload[key] = value;
    }
}




async function request(){
    let response;
    if (method == "GET" || method == "DELETE"){
        response = await fetch(link, {
            method: method,
            headers: {"Content-Type": "application/json"}
        });
    } else {
        response = await fetch(link, {
            method: method,
            headers: {"Content-Type": "application/json"},
            body: JSON.stringify(payload), // body data type must match "Content-Type" header
        });
    }
    const data = await response.json();
    

    if (Math.trunc(response.status / 100) != 2){
        document.getElementById("response").innerHTML = `bad request - ${response.status}`
    }
    else{
        document.getElementById("response").innerHTML = JSON.stringify(data)
    }
    return data;

}